#!/usr/bin/env python
#coding:utf-8
import cgi,web,pymongo
from bson import json_util 
from utils import getVcodeImage,render
import tags,book,rec
from settings  import sina_cfg,config
from weibopy.auth import OAuthHandler
from weibopy.api import API


urls = (
"/", "index",
"/search(.*)", "search",
"/sinaauth","sinaauth" ,
"/sinaauth_cbk","sinaauth_cbk" ,   
"/logout","logout" ,  
"/tags", tags.app_tags,
"/book",book.app_book,
"/rec", rec.app_rec,
"/image/(.*)","image",
"/message(.*)","message",
"/about","about",
"/validatecode","validatecode",
)

 
'''系统首页'''
class index:
    def GET(self):
        session = web.ctx.session
        access_token=session.get('access_token',None)
        session.access_token = access_token
        return render.index(config=config,session=session)



class sinaauth:
    def GET(self):
        session = web.ctx.session
        access_token=session.get('access_token',None)
        if not access_token:
            auth = OAuthHandler(sina_cfg['CONSUMER_KEY'],sina_cfg['CONSUMER_SECRET'],web.ctx.get('homedomain')+'/sinaauth_cbk')
            #获得新浪微博的认证url地址
            auth_url = auth.get_authorization_url()
            #在session中保存request_token，用于在新浪微博认证通过后换取access_token
            session.request_token=auth.request_token
            web.seeother(auth_url)
        else:
            auth = OAuthHandler(sina_cfg['CONSUMER_KEY'],sina_cfg['CONSUMER_SECRET'])
            auth.access_token=access_token
            api=API(auth)
            user=api.verify_credentials()
            return render.index(user=user)
        

class sinaauth_cbk:
    def GET(self):
        print "cbk....."
        session = web.ctx.session    
        try:
            ins=web.input()
            oauth_verifier=ins.get('oauth_verifier',None)
            request_token=session.get('request_token',None)
            auth=OAuthHandler(sina_cfg['CONSUMER_KEY'],sina_cfg['CONSUMER_SECRET'])
            auth.request_token=request_token
            #通过oauth_verifier来获取access_token
            access_token=auth.get_access_token(oauth_verifier)
            session.access_token=access_token
            web.seeother("/")
        except Exception:
            web.header("Content-Type", "text/html;charset=utf-8")
            return ':-( 出错了'

class logout:
    def GET(self):
         session = web.ctx.session
         session.access_token = None
         session.request_token = None
         web.seeother('/')

        
        
         
''' 读取图片流'''    
class image:
    def GET(self,id):
        if not id or id=="10000":
            raise web.seeother("/static/images/default_pic.gif",absolute=True);
            
        #web.header('Transfer-Encoding','chunked')  
        web.header('Content-type','image/jpeg')
        web.header('Cache-Control','public')
        imgData = None
        try:
            fs = gridfs.GridFS(FSDB,collection="photo")
            img = fs.get(id)
            imgData = img.read()
            web.header("Content-Length",len(imgData))
            return imgData
        except Exception:  
            raise web.seeother("/static/images/default_pic.gif",absolute=True); 
        

class message:
    def GET(self,msg):
        if not msg:
            msg = u'''
呃…抱歉，找不到你要的页面……<br />
您要查看的网页可能已被删除、或者名称已被更改，暂时不可用。<br />
如有问题请联系网站管理员<br />
感谢您的支持，喝杯茶再来吧!
            '''
        return render.message(msg=msg)
    
    
class about:
    def GET(self):
        return render.about()           
    
class validatecode:
    def GET(self):
        session = web.ctx.session
        cdata,ctext = getVcodeImage()
        session['vcode']=ctext
        return cdata
    

          
            
    
def notfound():
    return web.notfound("Sorry, the page you were looking for was not found.")


app = web.application(urls, locals())    

cgi.maxlen = 10 * 1024 * 1024 # 10MB

'''session defined'''
web.config.debug = False
session = web.session.Session(app, web.session.DiskStore('sessions'), {'count': 0})    

def session_hook():
    web.ctx.session = session

app.add_processor(web.loadhook(session_hook))



if __name__ == "__main__":
    #web.wsgi.runwsgi = lambda func, addr=None: web.wsgi.runfcgi(func, addr)
    app.run()
